// 用户标签选择

import {
  customer
} from '../../../js/modules/customer'

const componentCallback = require('../../js/componentCallback')
const componentBehavior = require('../../../js/common/ComponentBehavior')

Component({
  /**
   * 组件的属性列表
   */
  properties: {},

  behaviors: [componentCallback, componentBehavior],

  /**
   * 组件的初始数据
   */
  data: {
    tagList: [],
    selectedTagList: [],
    selectedTagName: '',
    tagListCache: []
  },

  lifetimes: {
    attached() {
      this.getData()
    }
  },
  observers: {
    selectedTagList(selectedTagList) {
      let selectedTagName = selectedTagList.map(item => {
        return item.Name
      }).join(',')
      this.setData({
        selectedTagName
      })
    },
    showComponent(showComponent) {
      if (showComponent) {
        let component = this.selectComponent('#tagSelector')
        component.show()
      }
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    showComponent() {
      this.setData({
        tagListCache: this.data.tagList
      })
    },
    getData() {
      customer.getCustomerTagList().then((res) => {
        this.setData({
          tagList: res.Content
        })
      })
    },
    // 选择标签
    selectTag(e) {
      let {
        index,
        tagindex
      } = e.currentTarget.dataset
      let {
        tagList
      } = this.data
      // 取反两次转化为布尔值
      let selected = !!tagList[index].data[tagindex].selected
      tagList[index].data[tagindex].selected = !selected
      this.setData({
        tagList
      })
    },
    // 选择完成后的方法
    selectedTag() {
      let {
        tagList
      } = this.data
      let selectedTagList = []
      tagList.map((item) => {
        item.data.map((tag) => {
          if (tag.selected) {
            selectedTagList.push(tag)
          }
        })
      })
      this.setData({
        selectedTagList,
        tagListCache: []
      })
      let component = this.selectComponent('#tagSelector')
      component.setData({
        showComponent: false
      })
      let selectedTagName = this.data.selectedTagName
      this.$$success({
        selectedTagList,
        selectedTagName
      })
    },
    // 停止选择
    stopSelectTag() {
      let tagListCache = this.data.tagListCache
      console.log(tagListCache)
      this.setData({
        tagList: tagListCache,
        tagListCache: []
      })
      this.$$fail()
    },
    reset() {
      let tagList = this.data.tagList
      tagList = tagList.map((item) => {
        item.data = item.data.map((tag) => {
          tag.selected = false
          return tag
        })
        return item
      })
      this.setData({
        tagList,
        selectedTagList: [],
        selectedTagName: '',
        tagListCache: []
      })
    }
  }
})